package com.wanlong.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wanlong.pojos.Bill;
import com.wanlong.pojos.Billitems;
import com.wanlong.pojos.BillitemsExample;
import com.wanlong.pojos.Owner;
import com.wanlong.service.BillService;
import com.wanlong.service.BillitemsService;
import com.wanlong.service.OwnerService;
import com.wanlong.util.FyResult;

/**
 * @author Tom
 * @category 未缴费账单控制器
 *
 */
@Controller
public class BillController {

	@Autowired
	private BillService billService;
	@Autowired
	private BillitemsService bitemService;
	@Autowired
	private OwnerService oService;

	private SimpleDateFormat cx = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * @category 跳转至业主未缴费展示页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/unpay")
	public String unpay(Model model) {
		// SimpleDateFormat cx = new SimpleDateFormat("yyyy-MM-dd");
		String start = "2010-01-01";
		String stop = cx.format(new Date());
		List<Owner> list = billService.findByOwner();
		model.addAttribute("list", list);
		model.addAttribute("start", start);
		model.addAttribute("stop", stop);
		model.addAttribute("inputname", "请输入姓名");
		return "unpay";

	}

	/**
	 * @category 通过给定时间范围展示和业主模糊姓名联合查询缴费信息
	 * @param model
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/unpaytime")
	public String unpayByTime(Model model, HttpServletRequest request, HttpSession session) throws ParseException {
		// 获取分页参数设置每页展示的个数
		int pageSize = (int) session.getAttribute("pageSize");
		// 获取分页参数设置传进来的页码是多少
		int pageNum = (int) session.getAttribute("pageNum");
		// 将字符串转换为日期对象
		Date start = cx.parse(request.getParameter("start"));
		Date stop = cx.parse(request.getParameter("stop"));
		// System.out.println(request.getParameter("start"));
		String name = request.getParameter("username");
		// System.out.println(name);
		// 账单的时间用于和stop和start比较
		Date billdate;
		// 开始时间戳
		long startTime = start.getTime();
		// 结束时间戳
		long stopTime = stop.getTime();
		long billtime;
		// 用该list给owner对象的billlist设值
		List<Bill> billlist = new ArrayList<>();
		// 查找所有
		List<Owner> list1 = billService.findByOwner();
		List<Owner> list = new ArrayList<>();
		// 生成要返回的list
		for (int i = 0; i < list1.size(); i++) {
			double total = 0;
			// 循环遍历得到的所有owner对象
			for (int j = 0; j < list1.get(i).getBill().size(); j++) {
				//获得owner单个订单的时间戳
				billdate = cx.parse(list1.get(i).getBill().get(j).getBilltime());
				billtime = billdate.getTime();
				//判断订单的时间戳是否在指定的范围内，并且该owner的姓名要包含指定的字符串
				try {
					if (billtime >= startTime && billtime <= stopTime && list1.get(i).getOname().contains(name)) {
						// 如果满足上述条件，则将该条订单信息添加到billlist中
						billlist.add(list1.get(i).getBill().get(j));
						// 计算总价
						total += list1.get(i).getBill().get(j).getBillitem().getBillitemmoney();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// 如果该业主有未缴纳的账单，给该业主对象设置未缴纳账单，并将该对象放入要传给前端的list中
			if (billlist.size() > 0) {
				list1.get(i).setTotal(total);
				list1.get(i).setBill(billlist);
				list.add(list1.get(i));
			}
			// 这里不能使用clear() 用list.clear()方法清空list；用此方法，其它引用该list的值也会变成空。
			billlist = new ArrayList<>();
		}
		if (list.size() < 1) {

			model.addAttribute("nolist", "没有查到相关信息呦，请您重新输入查询条件");
		}
		// 计算查询总数
		double listnum = list.size();
		int totalnum = (int) Math.ceil(listnum / pageSize);
		List<Owner> list2 = FyResult.getOwnerList(pageSize, pageNum, list, "f");
		// System.out.println(list.size());
		session.setAttribute("start", request.getParameter("start"));
		session.setAttribute("stop", request.getParameter("stop"));
		model.addAttribute("list", list2);
		model.addAttribute("name", name);
		model.addAttribute("totalnum", totalnum);
		session.setAttribute("pageSize", pageSize);
		session.setAttribute("pageNum", pageNum);
		session.setAttribute("findList", list);
		return "unpay";

	}

	/**
	 * @category 收费项目管理界面
	 * @param model
	 * @return
	 */
	@RequestMapping("/sfmanage")
	public String shoufeiguanli(Model model) {
		BillitemsExample example = new BillitemsExample();
		List<Billitems> list = bitemService.selectByExample(example);
		model.addAttribute("list", list);
		return "sfmanage";

	}

	/**
	 * @category 添加新的收费项目
	 * @param model
	 * @param billitem
	 * @return
	 */
	@RequestMapping("/addbillitem")
	public String addbillitem(Model model, Billitems billitem) {
		// 判断添加的收费项目是否为一次性收费
		if (billitem.getBillitemtype().equals("一次性")) {
			Date d = new Date();
			// 生成一次性收费的时间
			// SimpleDateFormat itemtime = new SimpleDateFormat("yyyy-MM-dd");
			String time = cx.format(d);
			billitem.setBillitemtime(time);
			// 添加到数据库
			bitemService.insert(billitem);
			// 从数据库查刚刚添加的收费项目
			Billitems item = bitemService.selectByNameAndTime(billitem.getBillitemname(), time);
			// 给所有的业主添加这个费用收费
			List<Owner> olist = oService.selectByExample();
			int[] all = new int[olist.size()];
			// 给数组all赋值业主的id
			for (int i = 0; i < all.length; i++) {
				all[i] = olist.get(i).getOid();
			}
			Bill bill = new Bill();
			bill.setBillitemid(item.getBillitemid());
			bill.setPaystatus("未缴纳");
			bill.setBilltime(time);
			for (int i = 0; i < all.length; i++) {
				bill.setUid(all[i]);
				billService.addBill(bill);
			}
			return "redirect:sfmanage.action";
		}
		bitemService.insert(billitem);
		return "redirect:sfmanage.action";
	}

	/**
	 * @category 搜索后展示缴费
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/showbyname")
	public String showbyname(Model model, HttpServletRequest request, HttpSession session) {
		int pageSize = (int) session.getAttribute("pageSize");
		int pageNum = (int) session.getAttribute("pageNum");
		String name = request.getParameter("username");
		// System.out.println(name);
		List<Owner> list1 = billService.findByOwner();
		List<Owner> list2 = FyResult.getOwnerList(pageSize, pageNum, list1, "f");
		// System.out.println(list1.size());
		List<Owner> list = new ArrayList<>();
		for (int i = 0; i < list2.size(); i++) {
			// System.out.println(list1.get(i).getOname());
			if (list1.get(i).getOname().contains(name)) {

				list.add(list1.get(i));
			}
		}
		double listnum = list1.size();
		int totalnum = (int) Math.ceil(listnum / pageSize);
		session.setAttribute("findList", list);
		session.setAttribute("pageSize", pageSize);
		session.setAttribute("pageNum", pageNum);
		model.addAttribute("list", list);
		model.addAttribute("inputname", name);
		model.addAttribute("totalnum", totalnum);
		return "unpay";
	}

	/**
	 * @category ajax搜索
	 * @param name
	 * @return
	 */
	@RequestMapping("/showname")
	public @ResponseBody List<Owner> showname(String name) {
		System.out.println("进来了");
		List<Owner> list1 = oService.selectByExample();
		List<Owner> list = new ArrayList<>();
		for (int i = 0; i < list1.size(); i++) {
			if (list1.get(i).getOname().contains(name)) {

				list.add(list1.get(i));
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/unpayfy")
	public String unpayfy(Model model, HttpSession session, int pageSize, int pageNum, String type,
			HttpServletRequest request) {
		System.out.println(pageNum);
		String stop;
		String start;
		// SimpleDateFormat cx = new SimpleDateFormat("yyyy-MM-dd");
		if (session.getAttribute("stop") != null) {
			stop = (String) session.getAttribute("stop");
		} else {
			stop = cx.format(new Date());
		}
		if (session.getAttribute("start") != null) {
			start = (String) session.getAttribute("start");
		} else {
			start = "2010-01-01";
		}

		List<Owner> list1 = new ArrayList<>();
		if (session.getAttribute("findList") != null) {

			list1 = (List<Owner>) session.getAttribute("findList");
		} else {
			list1 = billService.findByOwner();
		}
		double listnum = list1.size();
		int totalnum = (int) Math.ceil(listnum / pageSize);
		List<Owner> list = FyResult.getOwnerList(pageSize, pageNum, list1, type);
		if (type.equals("z")) {

			++pageNum;
			if (pageNum > totalnum) {
				pageNum = totalnum;
			}
		}
		if (type.equals("j")) {

			--pageNum;
			if (pageNum < 1) {

				pageNum = 1;
			}
		}
		if(type.equals("f")) {
			if(pageNum<1) {
				
				pageNum=1;
			}
			if(pageNum>totalnum) {
				pageNum = totalnum;
			}
			
		}
		model.addAttribute("list", list);
		session.setAttribute("stop", stop);
		session.setAttribute("start", start);
		session.setAttribute("pageSize", pageSize);
		session.setAttribute("pageNum", pageNum);
		model.addAttribute("totalnum", totalnum);
		return "unpay";

	}

}
